﻿using System;
using System.Collections.Generic;
using System.Text;
using Graffiti.Core;
using System.Web;
using System.Collections.Specialized;

namespace GraffitiExtras.Plugins.MobileThemeSelector
{
    public class MobileThemeSelector : GraffitiEvent
    {
        public string MOBILETHEMENAME;

        public override string Name
        {
            get
            {
                return "Mobile Theme Selector";
            }
        }

        public override string Description
        {
            get
            {
                return
                    "Plug-in to redirect all requests from mobile devices to mobile theme. " +
                    "Done by <a href=\"http://nayyeri.net\">Keyvan Nayyeri</a>.";
            }
        }

        public override bool IsEditable
        {
            get
            {
                return true;
            }
        }

        protected override NameValueCollection DataAsNameValueCollection()
        {
            NameValueCollection nvc = base.DataAsNameValueCollection();
            nvc["MOBILETHEMENAME"] = MOBILETHEMENAME;

            return nvc;
        }

        public override StatusType SetValues(HttpContext context, NameValueCollection nvc)
        {
            base.SetValues(context, nvc);
            MOBILETHEMENAME = nvc["MOBILETHEMENAME"];
            return StatusType.Success;
        }

        protected override FormElementCollection AddFormElements()
        {
            FormElementCollection fec = new FormElementCollection();

            fec.Add(new TextFormElement("MOBILETHEMENAME", "Mobile Theme Name", "Mobile theme name (i.e. Mobile)"));
            return fec;
        }

        public override void Init(GraffitiApplication ga)
        {
            ga.BeginRequest += new EventHandler(ga_BeginRequest);
        }

        void ga_BeginRequest(object sender, EventArgs e)
        {
            try
            {
                if ((HttpContext.Current.Request.UserAgent.IndexOf("IEMobile") > -1) ||
                    (HttpContext.Current.Request.Browser.IsMobileDevice))
                {
                    GraffitiContext.Current.Theme = MOBILETHEMENAME;
                    Log.Info("Mobile Theme Selector Plug-In",
                        string.Format
                            ("Mobile Theme Selector redirected a request to mobile theme. " +
                            "User agent was {0}.",
                            HttpContext.Current.Request.UserAgent));
                }
            }
            catch (Exception ex)
            {
                Log.Error("Mobile Theme Selector Plug-In", ex.Message + ex.StackTrace);
            }
        }
    }
}
